/*
 * Copyright 2010 Chad Retz
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.jdocng.log;

import java.util.ServiceLoader;

import org.jdocng.shared.Configuration;
import org.jdocng.shared.model.Logger;

/**
 * Factory to load the logger. It first attempts to use
 * {@link Configuration#getLogger()} and attempts to load it
 * as a qualified class name. If not present, all {@link ServiceLoader}
 * references to {@link Logger} compare the configuration
 * value with {@link Logger#getShortName()}. Otherwise, just
 * the first SPI class is used. The default in this distribution is
 * {@link org.jdocng.log.stdout.StdoutLogger}.
 *
 * @author Chad Retz
 */
public class LoggerFactory {

    private static ServiceLoader<Logger> loggerLoader = 
            ServiceLoader.load(Logger.class);
    
    /**
     * Build a new instance of a logger. See the class comment
     * for more information.
     * 
     * @param configuration
     * @return
     * @throws LoggerNotFoundException
     */
    public static Logger buildLogger(Configuration configuration)
            throws LoggerNotFoundException {
        //not there? load first from service loader
        if (configuration.getLogger() == null) {
            for (Logger logger : loggerLoader) {
                return logger;
            }
            throw new LoggerNotFoundException("Unable to find suitable logger");
        }
        //try what was passed in
        try {
            return (Logger) Class.forName(configuration.getLogger()).newInstance();
        } catch (Exception e) {
            //welp, just try short name
            for (Logger logger : loggerLoader) {
                if (configuration.getLogger().equals(logger.getShortName())) {
                    return logger;
                }
            }
            //error
            throw new LoggerNotFoundException("Class name and/or short name '" +
                    configuration.getLogger() + "' not found or couldn't be loaded", e);
        }
    }
    
    private LoggerFactory() {
    }
}
